package main

import (
	"bufio"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"
)

func main() {
	filename := "G:\\workspace_gitee\\golang\\golang-web\\test\\file.txt"
	outfile := "G:\\workspace_gitee\\golang\\golang-web\\test\\fileout.txt"
	fileNotExist := "G:\\workspace_gitee\\golang\\golang-web\\test\\file_not_exist.txt"

	content, err := ioutil.ReadFile(filename)
	if err != nil {
		log.Fatalln("Error reading file", filename)
	}

	fmt.Println(string(content))
	lines := strings.Split(string(content), "\n")
	for _, value := range lines {
		fmt.Println(value)
	}

	// 检查文件是否存在
	if _, err := os.Stat(fileNotExist); os.IsNotExist(err) {
		fmt.Println(">>>")
		fmt.Println("File: junk.foo does not exist")
	}
	// 处理大文件
	ProcessingLargeFiles(filename)

	write2file(outfile, content)
	// 文件续写
	append2file(outfile)
	// 使用文件路径
	useFilePath()
}

func ProcessingLargeFiles(filename string) {
	// 逐行处理大文件
	file, err := os.Open(filename)
	if err != nil {
		fmt.Println("Error opening file: ", err)
	}
	defer file.Close() // see explanation below

	// Use bufio scanner, the default Scan method is by line
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		fmt.Println(line)
	}
}

func write2file(outfile string, content []byte) {

	err := ioutil.WriteFile(outfile, content, 0644)
	if err != nil {
		fmt.Println("Error writing file: ", err)
	} else {
		fmt.Println(">>>")
		fmt.Println("Created: ", outfile)
	}
}

func append2file(outfile string) {
	af, err := os.OpenFile(outfile, os.O_APPEND|os.O_WRONLY, 0644)
	if err != nil {
		fmt.Println("Error appending to file:", err)
	}
	defer af.Close()
	if _, err = af.WriteString("Appending this text"); err != nil {
		fmt.Println("Error writing to file:", err)
	}
}

func useFilePath() {
	// a\b\file.ext
	filename := filepath.Join("a", "b", "file.txt")
	if _, e := os.Stat(filename); os.IsNotExist(e) {
		fmt.Println(filename + "文件不存在")
	} else {
		fmt.Println(filename + "文件存在")
	}

}
